from re import search

from fastapi import APIRouter, Query,UploadFile
from tortoise.expressions import Q

from app.settings import settings
from app.controllers.orders.goods import orders_goods_controller
from app.schemas.base import Success, SuccessExtra,Fail
from app.schemas.orders import *
from app.models.customer import CustomerUser
from app.models.goods import Goods
orders_goods_router = APIRouter()
model_name = "发货"


@orders_goods_router.get("/list", summary=f"查看{model_name}列表")
async def do_car_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(10, description="每页数量"),
        user_name: str = Query(None, description=f"用户姓名"),
        goods_name: str = Query(None, description=f"商品名称"),
):
    search_user_ids = []
    search_goods_ids = []
    if user_name:
        search_users = await CustomerUser.filter(name__contains=user_name).values("id")
        search_user_ids = {orders['id'] for orders in search_users}  # 获取所有的 user_id
    if goods_name:
        search_goods = await Goods.filter(name__contains=goods_name).values("id")
        search_goods_ids = {orders['id'] for orders in search_goods}  # 获取所有的 user_id
    q = Q(is_express=1)
    if user_name:
        q &= Q(user_id__in=search_user_ids)
    if goods_name:
        q &= Q(goods_id__in=search_goods_ids)
    total, data = await orders_goods_controller.do_list(page=page, page_size=page_size, search=q)

    user_ids = {orders['user_id'] for orders in data}  # 获取所有的 user_id
    goods_ids = {orders['goods_id'] for orders in data}  # 获取所有的 goods_id

    users = await CustomerUser.filter(id__in=user_ids)
    goods = await Goods.filter(id__in=goods_ids)
    users_dict = {user.id: user.name for user in users}
    for car in data:
        car['user_name'] = users_dict.get(car['user_id'], "已删除用户")
    goods_dict = {good.id: good.name for good in goods}
    for car in data:
        car['goods_name'] = goods_dict.get(car['goods_id'], "已删除商品")
    goods_dict2 = {good.id: good.cover for good in goods}
    for car in data:
        car['goods_cover'] = goods_dict2.get(car['goods_id'], "")

    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)


